package com.my.activiti.timer;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.ProcessEngineImpl;
import org.activiti.engine.task.Task;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Timer {

	@Resource
	private RepositoryService repositoryService;
	@Resource
	private RuntimeService runtimeService;
	@Resource
	private TaskService taskService;
	@Resource
	private FormService formService;
	@Resource
	private HistoryService historyService;
	@Resource
	private ProcessEngine processEngine;

	@Test
	public void test() throws InterruptedException {
		ProcessEngineImpl engine = (ProcessEngineImpl) ProcessEngines
				.getDefaultProcessEngine();

		// 启动JobExecutor
		System.out.println("启动JobExecutor...");
		engine.getProcessEngineConfiguration().getJobExecutor().start();

		RepositoryService repositoryService = engine.getRepositoryService();
		RuntimeService runtimeService = engine.getRuntimeService();
		TaskService taskService = engine.getTaskService();

		// 部署流程
		System.out.println("部署流程...");
		repositoryService.createDeployment()
				.addClasspathResource("bpmn/startTimerEvent01.bpmn20.xml")
				.deploy();

		// 启动流程
		System.out.println("开始启动流程...");
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("myDate1", "2016-06-13T20:10:00");
		variables.put("myDate2", "2015-06-13T20:11:00");
		variables.put("myBean", new MyBeanStartTimerEvent());
		runtimeService
				.startProcessInstanceByKey("startTimerEvent01", variables);

		// 查询第一个任务（需要等到第一个定时器触发后才能得到任务）
		Thread.sleep(1000 * 60);

		Task task = taskService.createTaskQuery().singleResult();
		System.out.println("task = " + task);
		System.out.println("任务ID：" + task.getId() + "  任务名称：" + task.getName());
		taskService.complete(task.getId());

		// 重置第二个定时器的时间
		Thread.sleep(1000 * 5);
		Map<String, Object> variables2 = new HashMap<String, Object>();
		variables2.put("myDate2", "2016-06-13T20:13:00");
		runtimeService.setVariables(task.getExecutionId(), variables2);

		// 流程结束
		System.out.println("流程结束...");
	}

}
